package com.mriassl.rabbitmq.rpc;

import java.io.IOException;
import java.util.Scanner;

import com.mriassl.rabbitmq.base.BaseConnection;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class RPCClient extends BaseConnection {
	
	private String QUEUE_NAME;
	
	public RPCClient() throws Exception {
		init();
		QUEUE_NAME = channel.queueDeclare().getQueue();
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
				String message = new String(body, "UTF-8");
				System.out.println("RPCClient call server,then return info:"+message+" corelationId:"+properties.getCorrelationId());
			}
		};
		channel.basicConsume(QUEUE_NAME, true, consumer);
	}

	public void call(String msg) throws Exception {
		System.out.println("msg:"+msg);
		BasicProperties props = new BasicProperties.Builder().correlationId(QUEUE_NAME).build();
		channel.basicPublish("", RPCConsts.RPC_QUEUE_NAME, props, msg.getBytes("UTF-8"));
	}
	
	public static void main(String[] args) throws Exception {
		RPCClient client = new RPCClient();
		Scanner input = new Scanner(System.in);
        String val = null;
        do{
            val = input.next();
            client.call(val);
        }while(!val.equals("#"));
        input.close();
	}
	
}
